//Code credit to http://www.devx.com/wireless/Article/40842
//Modified to work with calendar events by Ethan Baer

package nmsu.ppe.agendabuddy;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter
{
        //Event Keys
        public static final String KEY_EVENTID = "_id";
        public static final String KEY_DATE = "date";
        public static final String KEY_STARTTIME = "time";
        public static final String KEY_DURATION = "duration";                   //deprecated
        public static final String KEY_DESCRIPTION = "description";
        public static final String KEY_DATEMODIFIED = "dateModified";
        public static final String KEY_COMMENT = "comment";                             //deprecated
        public static final String KEY_ORIGIN = "origin";                               //source of event (app, facebook, google, etc.)
        public static final String KEY_REMINDER = "reminder";                   //deprecated?
        
        //Account Keys -- deprecated
        /*
        public static final String KEY_USERNAME = "username";
        public static final String KEY_PASSWORD = "password";
        public static final String KEY_ADDRESS = "account address";
        
        //Reminder Keys -- deprecated for now
        public static final String KEY_REMINDERID = "_rid";
        public static final String KEY_REPEATING = "repeats";
        public static final String KEY_INTERVAL = "repeatInterval";
        public static final String KEY_TEXT = "reminderText"; // I don't think this is necessary
        */
        
        //Database Info
        private static final String TAG = "DBAdapter";
        private static final String DATABASE_NAME = "calendar";
        private static final String DATABASE_TABLE_EVENTS = "events";
        private static final String DATABASE_TABLE_REMINDER = "reminder";
        private static final int DATABASE_VERSION = 1;

        //Database create statement
        private static final String DATABASE_CREATE =
                        "create table events (_id integer primary key autoincrement, "
                                        + "date text not null, "
                                        + "time text not null, "
                                        + "description text not null,"
                                        + "dateModified text not null,"
                                        + "origin text not null"
                                        + ");";
        
        /* Uncommented because reminders were removed
        private static final String DATABASE_CREATE_1 =
                        "create table events (_id integer primary key autoincrement, "
                                        + "date text not null,"
                                        + "time text not null, "
                                        + "description text not null," 
                                        + "duration text,"
                                        + "dateModified text not null,"
                                        + "comment text,"
                                        + "origin text not null,"
                                        + "reminder"
                                        + ");";
        private static final String DATABASE_CREATE_2 =
                        "create table reminder (_rid integer primary key autoincrement, "
                                        + "date text not null," 
                                        + "repeats integer, "
                                        + "repeatInterval text not null,"
                                        + ");";
        */
        private final Context context;

        private DatabaseHelper DBHelper;
        private SQLiteDatabase db;
		  
/**
* @param ctx current ctx
**/

        public DBAdapter(Context ctx)
        {
                this.context = ctx;
                DBHelper = new DatabaseHelper(context);
        }
        private static class DatabaseHelper extends SQLiteOpenHelper
        {
/**
* @param context context for helper
**/
                DatabaseHelper(Context context)
                {
                        super(context, DATABASE_NAME, null, DATABASE_VERSION);
                }
					 
/**
* @param db database creation
**/					 
                @Override
                public void onCreate(SQLiteDatabase db)
                {
                        db.execSQL(DATABASE_CREATE);
                }
					 
					 
/**
* @param oldVersion used to store old version
* @param newVersion used to store new version
**/					 
					 
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion,
                                int newVersion)
                {
                        Log.w(TAG, "Upgrading database from version " + oldVersion
                                        + " to "
                                        + newVersion + ", which will destroy all old data");
                        db.execSQL("DROP TABLE IF EXISTS titles");
                        onCreate(db);
                }
        }
        /**
         * Open the database for reading and writing - the open() needs to be paired with a close() after database activity 
         * @return This DBAdapter object
         * @throws SQLException
         */
        public DBAdapter open() throws SQLException
        {
                db = DBHelper.getWritableDatabase();
                return this;
        }
        
        /**
         * Close the database
         */
        public void close()
        {
                DBHelper.close();
        }
        
        /**
         * Add an event to the database
         * @param date The date of the event in the form MM:DD:YYYY
         * @param time The time of the event in the form HH:MM in 24-hour format
         * @param description The text displayed for the event
         * @param dateModified The date the event was last modified - Note: not used in current version
         * @param origin The account the event was modified from - Note: not used in current version
         * @return The unique ID of the event in the database
         */
        public long addEvent(String date, String time, String description, String dateModified, String origin)
        {
                ContentValues initialValues = new ContentValues();
                initialValues.put(KEY_DATE, date);
                initialValues.put(KEY_STARTTIME, time);
                initialValues.put(KEY_DESCRIPTION, description);
                initialValues.put(KEY_DATEMODIFIED, dateModified);
                initialValues.put(KEY_ORIGIN, origin);
                
                return db.insert(DATABASE_TABLE_EVENTS, null, initialValues);
        }

        /**
         * Delete an event from the database
         * @param id The unique ID of the event
         * @return
         */
        public boolean deleteEvent(long id)
        {
                return db.delete(DATABASE_TABLE_EVENTS, KEY_EVENTID + "='" + id +"'", null) >= 0;
        }

        /**
         * Get all the events in the database
         * @return A Cursor object with all the events
         */
        public Cursor getAllEvents()
        {
                Cursor tempCursor = db.query(DATABASE_TABLE_EVENTS, new String[] {
                                KEY_EVENTID,
                                KEY_DATE,
                                KEY_STARTTIME,
                                KEY_DESCRIPTION,
                                KEY_DATEMODIFIED,
                                KEY_ORIGIN},
                                null,
                                null,
                                null,
                                null,
                                null);
                
                if (tempCursor != null) {
                        tempCursor.moveToFirst();
                }
                return tempCursor;
        }

        /**
         * Get the event corresponding to the unique ID
         * @param id The unique ID
         * @return A Cursor object with the event in it
         * @throws SQLException
         */
        public Cursor getEvent(long id) throws SQLException
        {
                Cursor tempCursor =
                                db.query(true, DATABASE_TABLE_EVENTS, new String[] {
                                                KEY_EVENTID,
                                                KEY_DATE,
                                                KEY_STARTTIME,
                                                KEY_DESCRIPTION,
                                                KEY_DATEMODIFIED,
                                                KEY_ORIGIN
                                },
                                KEY_EVENTID + "=" + id,
                                null,
                                null,
                                null,
                                null,
                                null);
                if (tempCursor != null) {
                        tempCursor.moveToFirst();
                }
                return tempCursor;
        }

        /**
         * Get all events on a day
         * @param date_of_day The data of the day in the form MM:DD:YYYY
         * @return A Cursor object with the events in it ordered from earliest to latest
         * @throws SQLException
         */
        public Cursor getEvent(String date_of_day) throws SQLException
        {
                Cursor tempCursor =
                                db.query(true, DATABASE_TABLE_EVENTS, new String[] {
                                                KEY_EVENTID,
                                                KEY_STARTTIME,
                                                KEY_DESCRIPTION
                                },
                                KEY_DATE + "='" + date_of_day + "'",
                                null,
                                null,
                                null,
                                KEY_STARTTIME + " ASC",
                                null);
                if (tempCursor != null) {
                        tempCursor.moveToFirst();
                }
                return tempCursor;
        }
        
        /**
         * Check if there are any events on a day
         * @param date_of_day The data of the day in the form MM:DD:YYYY
         * @return true if there are events or false if there are no events on the day
         */
        public boolean eventsOnDay(String date_of_day)
        {
                Cursor tempCursor =
                                db.query(true, DATABASE_TABLE_EVENTS, new String[] {
                                                KEY_DATE
                                },
                                KEY_DATE + "='" + date_of_day + "'",
                                null,
                                null,
                                null,
                                null,
                                null);
                if(tempCursor.moveToFirst()){
                        tempCursor.close();
                        return true;
                } else {
                        tempCursor.close();
                        return false;
                }
        }
        
        /**
         * Update an event - change values of an event
         * @param id The unique ID of the event
         * @param date The date of the event in the form MM:DD:YYYY
         * @param time The time of the event in the form HH:MM in 24 hour format
         * @param description The text displayed for the event
         * @return true if the update was successful and false if it was not successful
         */
        public boolean updateEvent(long id, String date,
                        String time, String description)
        {
                ContentValues args = new ContentValues();
                args.put(KEY_DATE, date);
                args.put(KEY_STARTTIME, time);
                args.put(KEY_DESCRIPTION, description);
                return db.update(DATABASE_TABLE_EVENTS, args,
                                KEY_EVENTID + "=" + id, null) > 0;
        }
}